#!/bin/bash

# 引入配置文件
source config.sh

# 日志文件路径
LOG_FILE="$LOG_DIR/deploy.log"

# 检查 PHP_VERSION 是否正确加载
if [ -z "$PHP_VERSION" ]; then
    echo "ERROR: PHP_VERSION is not set. Please check config.sh."
    exit 1
fi

# 创建日志目录
mkdir -p $LOG_DIR
touch $LOG_FILE

# 日志记录函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a $LOG_FILE
}

# 错误处理函数
error_exit() {
    log "ERROR: $1"
    exit 1
}

# 1. 系统更新
log "Updating system..."
sudo apt update && sudo apt upgrade -y || error_exit "Failed to update system."

# 2. 安装必要工具
log "Installing required tools..."
sudo apt install -y curl git unzip redis-server logrotate || error_exit "Failed to install tools."

# 3. 检查端口冲突
log "Checking port conflicts..."
sudo netstat -tuln | grep -E ':(80|443|8080|8081)' && error_exit "Port conflict detected."


# 5. 添加 PHP PPA 仓库
log "Adding PHP PPA repository..."
sudo add-apt-repository ppa:ondrej/php -y || error_exit "Failed to add PHP PPA."
sudo apt update

# 6. 安装 PHP 及相关扩展
log "Installing PHP $PHP_VERSION..."
sudo apt install -y \
    php$PHP_VERSION \
    php$PHP_VERSION-cli \
    php$PHP_VERSION-fpm \
    php$PHP_VERSION-mysql \
    php$PHP_VERSION-curl \
    php$PHP_VERSION-gd \
    php$PHP_VERSION-gmp \
    php$PHP_VERSION-mbstring \
    php$PHP_VERSION-xml \
    php$PHP_VERSION-zip \
    php$PHP_VERSION-bcmath \
    php$PHP_VERSION-redis \
    || error_exit "Failed to install PHP."

# 7. 配置 PHP 安全性
log "Configuring PHP security..."
PHP_INI_PATH="/etc/php/$PHP_VERSION/fpm/php.ini"
sudo sed -i "s/^;*expose_php.*/expose_php = Off/" $PHP_INI_PATH
sudo sed -i "s/^;*enable_dl.*/enable_dl = Off/" $PHP_INI_PATH
sudo sed -i "s/^;*disable_functions.*/disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source/" $PHP_INI_PATH
# 配置 PHP pathinfo
log "Enabling PHP pathinfo..."
sudo sed -i "s/^;*cgi.fix_pathinfo.*/cgi.fix_pathinfo=1/" $PHP_INI_PATH


# 9. 重启 PHP-FPM
log "Restarting PHP-FPM..."
sudo systemctl restart php$PHP_VERSION-fpm || error_exit "Failed to restart PHP-FPM."

# 10. 安装 MySQL 8
log "Installing MySQL 8..."
# 添加 MySQL APT 仓库
wget -c https://dev.mysql.com/get/mysql-apt-config_0.8.26-1_all.deb
sudo dpkg -i mysql-apt-config_0.8.26-1_all.deb
# 更新软件包列表
sudo apt update
# 安装 MySQL 服务器
sudo apt install -y mysql-server || error_exit "Failed to install MySQL 8."

# 11. 配置 MySQL 安全性
log "Configuring MySQL security..."
# 先设置密码
sudo mysql -u root <<EOF
ALTER USER 'root'@'localhost' IDENTIFIED BY '$DB_ROOT_PASS';
FLUSH PRIVILEGES;
-- 删除匿名用户
DELETE FROM mysql.user WHERE User='';
-- 禁止远程 root 登录
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
-- 删除测试数据库
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
-- 刷新权限
FLUSH PRIVILEGES;
EOF

log "MySQL 8 installation and security configuration completed."

# 12. 安装 Nginx
log "Installing Nginx..."
sudo apt install -y nginx || error_exit "Failed to install Nginx."

# 13. 配置 Nginx 基础设置
log "Configuring Nginx..."
sudo sed -i "s/# server_tokens off;/server_tokens off;/" /etc/nginx/nginx.conf
sudo nginx -t && sudo systemctl reload nginx || error_exit "Failed to reload Nginx."

# 14. 安装 Supervisor
log "Installing Supervisor..."
sudo apt install -y supervisor || error_exit "Failed to install Supervisor."

# 15. 安装 Composer
log "Installing Composer..."
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
HASH="$(wget -q -O - https://composer.github.io/installer.sig)"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); exit(1); } echo PHP_EOL;"
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer || error_exit "Failed to install Composer."
php -r "unlink('composer-setup.php');"

# 16. 配置 logrotate 管理日志文件
log "Configuring logrotate for log management..."
LOGROTATE_CONF="/etc/logrotate.d/laravel-deploy"
cat <<EOL | sudo tee $LOGROTATE_CONF > /dev/null
$LOG_DIR/*.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 640 root root
    sharedscripts
    postrotate
        if [ -f /run/nginx.pid ]; then
            sudo systemctl reload nginx > /dev/null 2>&1
        fi
    endscript
}
EOL

log "Environment deployment completed successfully!"